<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification;

/**
 * 调试接口
 */
class Test extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['testset', 'testget', 'push','push1'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['test2', 'push','push1'];

    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功'
        })
     */
    public function testset()
    {
        $params = $this->request->param();
        $params['createtime'] = date('Y-m-d H:i:s',time());
        Db::name('bluetooth_test')->insert($params);
        $this->success('保存成功');
    }

    /**
     * 无需登录的接口
     *
     */
    public function testget()
    {
        $params = $this->request->param();
        $page = isset($params['page'])&&is_numeric($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['pageSize'])&&is_numeric($params['pageSize']) ? $params['pageSize'] : 10;
        $list = Db::name('bluetooth_test')
        ->limit(($page - 1)*$pageSize,$pageSize)
        ->order('createtime desc')
        ->select();
        $data = [
                    'list'  => $list
                ];
        $this->success(__('success！'), $data);
    }

    /**
     * 需要登录的接口
     *
     */
    public function test2()
    {
        $str = '606E4120B7E8';
        
        die();
        $this->success('返回成功', ['action' => 'test2']);
    }

    /**
     * 需要登录且需要验证有相应组的权限
     *
     */
    public function test3()
    {
        $this->success('返回成功', ['action' => 'test3']);
    }

    /**
     * 测试推送消息
     * @return void
     */
    public function push(){
	    $params = $this->request->param();
	    if(empty($params['device_toke'])){
		    $this->success('参数错误', ['res' =>$params]);
	    }
	    $body  =  $params['body']?? '';
	    $title =  $params['title']?? '';
	    $deviceToken =  $params['device_toke']?? '';
        //try {
            $factory = (new Factory)->withServiceAccount(APP_PATH . 'neon-shelter-382006-firebase-adminsdk-hevyo-b3e0422a6a.json');
            $messaging = $factory->createMessaging();

            $message = CloudMessage::withTarget('token', $deviceToken)
                ->withNotification(Notification::create($title, $body))
                ->withData(['key' => 'value']);
            $re = $messaging->send($message);
            //$this->success('返回成功1', ['res1' => $re]);
       /* }catch (\Exception $e){
	        $this->success('返回失败2', ['file' => $e->getFile(),'line' => $e->getLine(),'msg' => $e->getMessage()]);

        }*/

        $this->success('返回成功3', ['msg' => '发送成功','re' => $re]);
    }

    public function push1(){
        $params  = $this->request->param();
        $token   = $params['token'] ?? '';
        $notify_server_key   = $params['notify_server_key'] ?? '';
        $notify_data = [
            'title' =>'title', 'body' => 'body of message.',
            'data' => [ 'page_type'=> 1, 'bid'=> 0, 'url'=> ''],
        ];
        if(empty($token)){
            $this->error(__('参数错误！'));
        }
        $res = $this->send_message($token, $notify_data,$notify_server_key);
        $this->success('返回成功', ['res' => $res]);
    }
    /**
     * 发送消息
     * @param string $token
     * @param array $notify_data = [
    'title' =>'title', 'body' => 'body of message.',
    'data' => [ 'page_type'=> 1, 'bid'=> 0, 'url'=> ''],
    ];
     * page_type 1 网页  2 详情 3 阅读页 4 邀请好友 5 福利中心 6 看海量视频 7 签到 8 推送 9 书城 10 书架
    11 网页跳出App 12 积分墙 13 下载墙 14 优惠券 15 VIP 16 建议反馈 17 GamePix页游 18 我的回复
     * @return bool
     * @Date 2021/4/2 9:56
     * @Author wzb
     */
    private function send_message($token = '', $notify_data = [],$notify_server_key = '')
    {
        if (!$token) {
            return false;
        }
        $notify_data['data']["click_action"] = 'FLUTTER_NOTIFICATION_CLICK';
        $notify_msg = [
            "notification" => [
                "title" => $notify_data['title'],
                "body" => $notify_data['body']
            ],
            "data" => $notify_data['data'],
            "to" => $token,
            "direct_book_ok" => true
        ];
        $data = json_encode($notify_msg);
        $notify_server_key = $notify_server_key ?? 'b81e247810713354d802c74558ff73e4c41afd99';
        $url = "https://fcm.googleapis.com/fcm/send";
        $headers = [
            "Authorization:key=" . $notify_server_key,
            "Content-Type:application/json"
        ];
        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            // 在尝试连接时等待的秒数
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT , 2);
            // 最大执行时间
            curl_setopt($ch, CURLOPT_TIMEOUT, 3);
            $result = curl_exec($ch);
            $respon = $result;
        } catch (\Exception $e) {
            $respon = $e->getMessage();
        }
        return $respon;
    }
}
